package com.zhu.SupermarketInventoryManagement.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhu.SupermarketInventoryManagement.dao.IAdminDao;
import com.zhu.SupermarketInventoryManagement.model.DO.AdminDO;
import com.zhu.SupermarketInventoryManagement.model.QO.AdminQO;
import com.zhu.SupermarketInventoryManagement.model.ResultCommon;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class LoginService {

    @Resource
    private IAdminDao adminDao;

    public ResultCommon<Object> login(@RequestBody AdminQO adminQO) {
        ResultCommon<Object> resultCommon = new ResultCommon<>();
        QueryWrapper<AdminDO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", adminQO.getUsername());
        wrapper.eq("password", adminQO.getPassword());
        AdminDO one = adminDao.getOne(wrapper);
        if (one != null) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            assert requestAttributes != null;
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            request.getSession().setAttribute("admin", one);
            resultCommon.setCode(0);
        } else {
            resultCommon.setCode(500);
        }
        return resultCommon;
    }
}
